using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.DeviceClassificationDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.DeviceClassificationDictionaryHandler
{
    /// <summary>
    /// 创建器械处理器
    /// </summary>
    public class CreateApparatusHandler : IRequestHandler<CreateApparatusCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Apparatus> _apparatusRepository;
        private readonly ILogger<CreateApparatusHandler> _logger;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="apparatusRepository">仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="mapper">对象映射器</param>
        public CreateApparatusHandler(
            IBaseRepository<Apparatus> apparatusRepository,
            ILogger<CreateApparatusHandler> logger,
            IMapper mapper)
        {
            _apparatusRepository = apparatusRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理创建器械请求
        /// </summary>
        /// <param name="request">创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public Task<ApiResult<int>> Handle(CreateApparatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 使用AutoMapper创建实体
                var apparatus = _mapper.Map<Apparatus>(request.ApparatusData);

                // 设置默认状态为启用(1)
                apparatus.Status = 1;
                apparatus.IsDeleted = false;
                apparatus.CreateTime = DateTime.Now;
                apparatus.UpdateTime = DateTime.Now;

                // 保存到数据库
                _apparatusRepository.Create(apparatus);

                _logger.LogInformation("成功创建器械 {Name}，ID: {Id}", apparatus.ApparatusName, apparatus.Id);

                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Msg = "创建成功",
                    Data = apparatus.Id
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建器械时发生异常");
                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "创建失败：系统内部错误",
                    Data = 0
                });
            }
        }
    }
}